import ArticleItem from '../ArticleItem'

import styles from './index.module.scss'
import {InfiniteScroll, PullToRefresh} from "antd-mobile";
import {useDispatch, useSelector} from "react-redux";
import {getArticleList} from "@/store/actions/home";
import {useHistory} from "react-router-dom";

const ArticleList = ({channelId}) => {
  const dispatch = useDispatch()
  const history = useHistory()
  // 1、从redux里面获取所有的文章列表信息 {0: {timeStamp: '', results: []}, 1: {timeStamp: '', results: []}}
  const {channelArticles} = useSelector(state => state.home);
  // 1、获取当前频道的文章列表信息
  //    用于界面渲染以及下一次接口请求使用时间戳字段(首次渲染没有值使用默认值即可)
  const currentChannelArticle = channelArticles[channelId] || {
    pre_timestamp: Date.now() + '',
    results: []
  }
  const {pre_timestamp, results} = currentChannelArticle

  async function loadMore() {
    // 使用上一次的时间戳字段进行数据的获取
    await dispatch(getArticleList(channelId, pre_timestamp))
  }

  // 判断当前页面是否还有数据
  const hasMore = pre_timestamp !== null

  // 下拉刷新功能
  const onRefresh = async () => {
    await dispatch(getArticleList(channelId, Date.now() + '')) // 获取最新的数据，因为当前的功能就是下拉刷新
  }

  const renderArticleList = () => {
    return results.map((item, index) => {
      // item项进行二次处理
      const {
        title,
        pubdate,
        comm_count,
        aut_name,
        cover: {type, images},
        art_id
      } = item

      //  把数据进行组合
      const articleData = {
        title,
        pubdate,
        comm_count,
        aut_name,
        type,
        images
      }

      return <div onClick={() => history.push(`/article/${art_id}`)} key={index} className={'article-item'}>
        <ArticleItem {...articleData} />
      </div>
    })
  }

  return (
    <div className={styles.root}>
      <PullToRefresh
        onRefresh={onRefresh}
      >
        {
          renderArticleList()
        }
        <InfiniteScroll loadMore={loadMore} hasMore={hasMore}/>
      </PullToRefresh>
    </div>
  )
}

export default ArticleList
